import shutil
from pathlib import Path

import aiofiles
from fastapi import UploadFile

from core.file_storage import ROOT_DATA_DIR
from util.xls2xlsx import XLS2XLSX


class FileManager:
    BASE_PATH = ROOT_DATA_DIR

    def __init__(self, category: str, quarter: str):
        """初始化并创建目录结构"""
        self.category = category
        self.quarter = quarter

        # 初始化路径
        root_dir_name = f"{self.quarter}_{self.category}"
        self.path = self.BASE_PATH / root_dir_name
        self.bid_path = self.path / "bid_documents"

        # 创建目录
        self.path.mkdir(parents=True, exist_ok=True)
        self.bid_path.mkdir(exist_ok=True)
        """
        /category_quarter
            tender.xlsx
            summary.xlsx
        /category_quarter/bid_documents
            bid1.xlsx
            bid2.xlsx
            ...
        """

    async def create_tender_document_file(self, file: UploadFile) -> Path:
        file_suffix = Path(file.filename).suffix
        file_name = f"tender{file_suffix}"
        file_path = self.path / file_name
        async with aiofiles.open(file_path, mode="wb") as f:
            content = await file.read()
            await f.write(content)

        xls2xlsx = XLS2XLSX(file_path)
        file_path = xls2xlsx.output_xlsx()
        return file_path

    async def create_bid_document_file(self, file: UploadFile) -> Path:
        file_suffix = Path(file.filename).suffix
        file_name = f"{file.filename}"
        if file_name in self.list_bid_document_names():
            base_name = Path(file.filename).stem
            count = 1
            while True:
                new_file_name = f"{base_name}_{count}{file_suffix}"
                if new_file_name not in self.list_bid_document_names():
                    file_name = new_file_name
                    break
                count += 1
        file_path = self.bid_path / file_name
        async with aiofiles.open(file_path, mode="wb") as f:
            content = await file.read()
            await f.write(content)

        xls2xlsx = XLS2XLSX(file_path)
        file_path = xls2xlsx.output_xlsx()
        return file_path

    async def create_bid_bargaining_file(self, file: UploadFile, bid_name: str) -> Path:
        file_suffix = Path(file.filename).suffix
        file_name = f"{bid_name}.bargaining{file_suffix}"
        file_path = self.bid_path / file_name
        async with aiofiles.open(file_path, mode="wb") as f:
            content = await file.read()
            await f.write(content)
        xls2xlsx = XLS2XLSX(file_path)
        file_path = xls2xlsx.output_xlsx()
        return file_path

    def list_bid_document_files(self) -> list[Path]:
        return list(self.bid_path.glob("*"))

    def list_bid_document_names(self) -> list[str]:
        return [p.name for p in self.bid_path.glob("*")]

    def get_bid_document_file(self, bid_name: str) -> Path | None:
        file_name = f"{bid_name}.xlsx"
        file_path = self.bid_path / file_name
        if file_path.exists():
            return file_path
        return None

    def get_summary_document_file(self) -> Path | None:
        file_path = self.path / "summary.xlsx"
        if file_path.exists():
            return file_path
        return None

    def create_summary_file_path(self) -> Path:
        return self.path / "summary.xlsx"

    def delete_all(self):
        if self.path.exists():
            shutil.rmtree(self.path)

    async def delete_bid_document(self, bid_name: str):
        bid_file_name = f"{bid_name}.xlsx"
        print(bid_file_name)
        bid_doc_path = self.bid_path / bid_file_name
        print(bid_doc_path)
        if bid_doc_path and bid_doc_path.exists():
            bid_doc_path.unlink()
        # xls记录
        bid_file_name_xls = f"{bid_name}.xls"
        bid_doc_path_xls = self.bid_path / bid_file_name_xls
        if bid_doc_path_xls and bid_doc_path_xls.exists():
            bid_doc_path_xls.unlink()

    async def delete_bid_bargaining_file(self, bid_name: str):
        bargaining_file_name = f"{bid_name}.bargaining.xlsx"
        bargaining_file_path = self.bid_path / bargaining_file_name
        if bargaining_file_path.exists():
            bargaining_file_path.unlink()
        # xls记录
        bargaining_file_name_xls = f"{bid_name}.bargaining.xls"
        bargaining_file_path_xls = self.bid_path / bargaining_file_name_xls
        if bargaining_file_path_xls.exists():
            bargaining_file_path_xls.unlink()
